(function (){

    /**
     * 展示提示信息
     * @param { } msg 
     */
  Rsd.alert= function (msg) {
      wx.hideLoading(),
      setTimeout(function(){

          wx.showToast({
              title: msg,
              icon: 'OK',
              image: '',
              duration: 2000,
              mask: true,
              success: function (res) {
              },
              fail: function (res) {
              },
              complete: function (res) {
              },
          });
          
      },100);
      
  };
  /**
   * 展示警告信息
   * @param {*} msg 
   * @param {*} callback 
   */
  Rsd.warn= function (msg,callback) {

      var _list = [];
      if(Rsd.isArray(msg))
      {
          _list = msg;
      }
      else
      {
          _list = msg.split("\r\n");
      }        
      wx.showModal({
          title: _list.length > 1 ?_list[0]:'提示信息',
          content: _list.length > 1?_list[1]:_list[0],
          "showCancel":false,
          success:function (res) {
              if(callback instanceof Function)
              {
                  callback();
              }
          },
          fail:function (res) {
              console.error(res);
          }
      });

  };
  /**
   * 展示错误信息
   * @param {*} msg 
   * @param {*} callback 
   */
  Rsd.error= function (msg,callback) {

      wx.showModal({
          title: '错误信息',
          content: msg,
          "showCancel":false,
          success:function (res) {
              if(callback instanceof Function)
              {
                  callback();
              }
          },
          fail:function (res) {
              console.error(res);
          }
      });
  };
   /**
   *  @param string msg 文本消息
   * @param int interval 延时
   * */
  Rsd.showLoading=function showLoading(msg,interval) {

      var _interval=0;
      if(Rsd.isNumber(interval))
      {
          _interval = interval;
      }
      if(!Rsd.isEmpty(msg)){

          if(Rsd.___last_loading_text == msg )
          {
              Rsd.___last_loading_count++;
          }
          else
          {
              setTimeout(function () {
                  wx.showLoading({
                      title: msg,
                      success:function () {
                          Rsd.___last_loading_count=0;
                          Rsd.___last_loading_text = msg;
                      }
                  });
              },_interval);
          }

      }

  };
  /**
   * @param boolean all 关闭全部
   * @param int interval 延时
  * */
  Rsd.hideLoading=function hideLoading(all,interval) {

      if ((all==undefined || all==null || !all) && Rsd.___last_loading_count > 0)
      {
          Rsd.___last_loading_count--;
          return;
      }
      var _interval=0;
      if(Rsd.isNumber(interval))
      {
          _interval = interval;
      }
      setTimeout(function () {
          wx.hideLoading({
              success:function () {
                  Rsd.___last_loading_count == 0;
                  Rsd.___last_loading_text = '';
              }
          });
      },_interval);
  };
 /**
   * 组织 form 属相EncType（content-type）为 application/x-www-form-urlencoded 提交数据
   * @param {*} obj 
   * @param {*} pre 
   */
  Rsd.toFormData =function toFormData(obj,pre) { 
      var _pre = pre || '';
      if (obj == undefined || obj==null) { 
          return '';
      } 
      if (typeof obj == "string") {
          if(_pre)
          {
              return _pre +"=" + obj.replace(/([\"\\])/g, "\\$1").replace(/(\n)/g, "\\n").replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "";
          }else
          {
              return "" + obj.replace(/([\"\\])/g, "\\$1").replace(/(\n)/g, "\\n").replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "";
          }
      
      }

      if (obj instanceof Array) {
          var r = [];
          for (var i = 0; i < obj.length; i++) {
              if (typeof (obj[i]) == 'function') {

                  continue;
              }
              if (typeof obj[i] == 'object') {
                  var _t = this.toFormDataString(obj[i], _pre + '[' + i + ']');
                  Array.prototype.push.apply(r, _t);
              }
              else {
                  r.push(this.toFormDataString(obj[i], _pre + '[' + i + ']'))
              }
          

              if (!_pre) {
                  r = r.join('&');
              }
          }
          
          //非对象类型的数组 没有处理为:[1,24,5] 格式

          return r;
      }

      if (typeof obj == "object") {
          var r = [];

          for (var k in obj) {
              if (typeof (obj[k]) == 'function') {
                  continue;
              }
              if ( obj[k]==null || typeof  obj[k] == "string") {

                  if(_pre)
                  {
                      r.push(_pre + '[' + k + ']' + "=" +  this.toFormDataString(obj[k]));
                  }else
                  {
                      r.push(k + "=" +  this.toFormDataString(obj[k]));
                  }
                  continue;
              }
              
              if(typeof obj[k] == 'object' )
              { 
                  if(_pre)
                  {
                      var _t = this.toFormDataString(obj[k],_pre + '[' + k + ']');
                      Array.prototype.push.apply(r , _t);
                  }else
                  {
                      var _t = this.toFormDataString(obj[k], k);
                      Array.prototype.push.apply(r , _t);
                  }
              }
              else
              {
                  if(_pre)
                  {
                      r.push(_pre + '[' + k + ']' + "=" +  this.toFormDataString(obj[k]));
                  }else
                  {
                      r.push(k + "=" +  this.toFormDataString(obj[k]));
                  }

              }

          }
          if(!_pre)
          {
              r = r.join('&');
          }
          //console.log(r);
          return r;
      }

      return obj.toString().replace(/\"\:/g, '":""');
  };

  /**
   * @public
   * @param config 将被合并到Ajax对象上
   * @param callback 回调函数
   * */
  Rsd.httpRequest = function request(config, data, callback,msg) {
      var _c = null;
      var _d = null;
      var _fn = null;
      for(var i in arguments)
      {
          if(_c == null && Rsd.isString(arguments[i]))
          {
              _c = {url:arguments[i]};
              continue;
          }
          if(_c == null && Rsd.isObject(arguments[i]))
          {
              _c = arguments[i];
              continue;
          }
          if(_d == null && Rsd.isObject(arguments[i]))
          {
              _d = arguments[i];
              continue;
          }
          if(_fn == null && Rsd.isFunction(arguments[i]))
          {
              _fn = arguments[i];
              continue;
          }
      }
      //
      if (_fn == null) {

          _fn = void(0);
      }
      if (_fn == null) {

          _fn = void(0);
      }

      _c = _c||{};
      _c.timer=0;//异常处理次数
      _c.data = _d||_c.data||{};
      if(_c.method=='POST')
      {
          //_c.data = Rsd.toFormData(_c.data);
      }
      _c.header = _c.header|| { 'Content-Type': 'application/x-www-form-urlencoded' };
     
      var token = app.token || wx.getStorageSync('token');
       //console.log('this is token:',token);
       if(token)
       {
           _c.header['token'] = token;
       }
       var app = Rsd.app||getApp();
       if(Rsd.isEmpty(_c.header.authorization) && app)
       {
          _c.header.authorization = app.authorization;
       }
       
      _c.success =_c.success || function  (res) {

          if(res.statusCode != '200' || res.data.code =="-1")
          {
              if( _c.timer < 4)
              {
                  _c.timer++;
                  setTimeout(function () {
                      wx.request(_c);
                  },500);

              }else {
                  Rsd.hideLoading();
                  Rsd.error('服务异常('+res.statusCode+')');
              }

              return;
          }

          var _rs = _fn(res.data);

          Rsd.hideLoading();

          if(res.data.success || _rs)
          {
              return;
          }

          Rsd.warn(res.data.msg);
      };
      _c.fail = _c.fail||function(res)
      {
          //延时0.5秒 再次请求一次
          if(_c.timer < 4)
          {
              _c.timer++;
              setTimeout(function () {
                  wx.request(_c);
              },500);

              return;
          }

          Rsd.hideLoading();

          var sys = wx.getAccountInfoSync();
          if(sys.miniProgram.envVersion=="develop")
          {
              Rsd.error('请求服务异常！('+Rsd.formatJson(res)+')');
          }
          else
          {
              Rsd.error('请求服务异常！');
          }
      }
      //console.log(_c);

      wx.showLoading(msg);
      _c.timer++;
      wx.request(_c);
  };
  /*
  *
  * */
  Rsd.httpRequest=function request(config, data, callback,msg) {
      var _c = null;
      var _d = null;
      var _fn = null;
      if(_c == null && Rsd.isString(config))
      {
        _c = {url:config,data:data}; 
      }
      if(_c == null && Rsd.isObject(config))
      {
          _c = Rsd.apply({},config); 
      }
      if(_d == null && Rsd.isObject(data))
      {
          _d = data; 
      }
    if(_fn == null && Rsd.isFunction(callback))
    {
        _fn = callback; 
    }   

      if (_fn == null) { 
          _fn = void(0);
      }

      if(Rsd.isEmpty(_c.url))
      {
        console.error('url is null',_c);
        console.trace(_c);
        return;
      }
      _c = _c||{};
      _c.timer=0;//异常处理次数
      _c.data = _d||_c.data||{};
      if(_c.method=='POST')
      {
         // _c.data = Rsd.toFormData(_c.data);
      } 
      _c.header = _c.header|| {'content-type':'application/x-www-form-urlencoded;charset=utf-8'};
      var token =  wx.getStorageSync('token'); 
       //console.log('this is token:',token);
       if(token)
       {
           _c.header['token'] = token;
       }

       var app = Rsd.app || Rsd.getApp();
       if(Rsd.isEmpty(_c.header.authorization) && app)
       {
          _c.header.authorization = app.authorization;
       }
      
      _c.success =_c.success || function  (res) {
      //console.log(res);
          if(res.statusCode != '200' || res.data.code =="-1")
          {
              if( _c.timer < 4){

                  _c.timer++;
                  setTimeout(function () {
                      wx.request(_c);
                  },500);

              }else {
                  Rsd.hideLoading();
                  Rsd.error('服务异常('+res.statusCode+')');
              }

              return;
          } 
          var _rs = _fn(res.data); 
          Rsd.hideLoading(); 
          if(res.data.success || _rs)
          {
              return;
          }
          //同意拦截错误处理
          if(this.app && this.app.onRequestError)
          {
              _rs = this.app.onRequestError(res.data);
          }
          if(_rs)
          {
              return;
          }
          if(res.data.data && res.data.data.Title && res.data.data.Message)
          {
              Rsd.warn([res.data.data.Title,res.data.data.Message]);
          }
          else
          {
              Rsd.warn(res.data.msg);
          }
      };
      _c.fail = _c.fail||function(res)
      {
          console.trace(_c);
          console.log(res);
          //延时0.5秒 再次请求一次
          if(_c.timer < 4)
          {
              _c.timer++;
              setTimeout(function () {
                  wx.request(_c);
              },500);

              return;
          }

          Rsd.hideLoading();

          var sys = wx.getAccountInfoSync();
          if(sys.miniProgram.envVersion=="develop")
          {
              Rsd.error('请求服务异常！('+Rsd.formatJson(res)+')');
          }
          else
          {
              Rsd.error('请求服务异常！');
          }
      }

      Rsd.showLoading(msg); 
      _c.timer++;
      wx.request(_c);
  };

  /**
   * @description 服务未加载完成时，有两次各延时1秒的处理
  *
  * */
  Rsd.requestService=function requestService(name, data, callback,msg) {

      if(Rsd.isEmpty(name))
      {
          throw new Error('param [name] is null when call  Rsd.requestService method.');
      }
      var _name = name.toLowerCase();
      var _group = _name.substr(0,_name.lastIndexOf('.'));
      var _method = _name.substr(_name.lastIndexOf('.')+1);

      var service = Rsd.services[_group];

      if(Rsd.isEmpty(service) )
      {
          var _error =  '服务['+_name+']不存在,请先注册';
          Rsd.warn(_error);
          console.error(_error);
          return;
      }

      var _fn = function () {

          var api = service.api[_method];
          if(Rsd.isEmpty(api))
          {

              var _error =  '服务['+_name+']不存在,请确认';
              Rsd.warn(_error);
              console.error(_error);
              return;
          }

          //console.log('request api '+_name );
          //参数整理
          //替换路径参数 
          var _url = api.server.url.toLowerCase(); 
          var _routeArgs = data||{};
          for(var s in _routeArgs)
          {
              if(Rsd.isString(s))
              {
                  if(_url.indexOf('{'+s.toLowerCase()+'}')>0)
                  {
                      _url = _url.replace('{'+s.toLowerCase()+'}',_routeArgs[s]); 
                      delete _routeArgs[s];
                  }
              
              }
              
          }  
          Rsd.httpRequest({url:_url,method:api.server.method||'POST'},data,callback,msg);
        
      }

      var _timer = 0;
      var _request = function () {

          if(Rsd.isEmpty(service.api[_method]))
          {
              //如果正在加载服务 延时200毫秒 最多延时5次 
              if(_timer>5)
              {
                  service.isLoading = false;
                  Rsd.warn('系统繁忙，请稍后再试');
                  return;
              }

              if(service.isLoading){

                  Rsd.sendInfoLog(_timer + '- call '+_name + ' => ' + service.group + ' loading api' );
                  setTimeout(_request,200);
                  _timer++;
              }
            
          }
          else
          {
              _fn();
          }

      }

      if(Rsd.isEmpty(service.api))
      {
          if(service.isLoading)
          {
              _request();

          }else
          {
              Rsd.loadServiceApi(service,_fn);
          }

      }
      else
      {
          _fn();
      }

  };

  /**
   * @description 获取服务
   */
  Rsd.getService = function(name)
  {
      if(Rsd.isEmpty(name))
      {
          throw new Error('param [name] is null when call  Rsd.getService method.');
      }
      var _name = name.toLowerCase();
      var _group = _name.substr(0,_name.lastIndexOf('.'));
      var _method = _name.substr(_name.lastIndexOf('.')+1);

      var service = Rsd.services[_group];
      if(Rsd.isEmpty(service) )
      { 
          var _error =  '服务['+_name+']不存在,请先注册';
          Rsd.warn(_error);
          console.error(_error);
          return null;
      }

      return  service.api[_method];
  };

  /** 
   * services:[{group:'',host:'',controller:'',index:'index',useSSL:true}]
   */
  Rsd.loadServices = function loadServices(services)
  { 
      var servicesList = []; 
      if(Rsd.isArray(services))
      {
         servicesList=services;
      }     

      Rsd.services = Rsd.services||{};  

      var _load = function(data)
      {
        var item = this;
          if(data.code =="-1" && _timer<4)
          {
              setTimeout(function(){_test.call(item)},200);
              return true;
          } 
          //探测成功
          var _url = item.host + item.controller + item.desc;
          Rsd.httpRequest({url:_url,method:'GET'},{},function(resp){
              if(resp.success)
              {
                Rsd.sendInfoLog('探测'+item.group+'成功，共 '+resp.data.length + ' API接口'); 
              }
              else
              {
                Rsd.sendErrorLog('探测'+item.group+ ('失败：'+resp.msg||'')); 
              }
            
            for(var i in resp.data)
            { 
                var apiItem = resp.data[i];
                 Rsd.services[item.group].api[apiItem.MethodName.toLowerCase()] = {
                  server:{
                    url:apiItem.Url,
                    method:apiItem.Method || 'GET',
                    //contentType:'application/json',
                    //dataType: 'json',
                    async:apiItem.IsAsync
                }
              };
            }
           
          },'连接远程服务');
         
      };
      var _textFail = function()
      {

          if(_timer<4)
          {
            var item = this;
              setTimeout(function(){_test.call(item)},500);
          }else
          {
              Rsd.warn('系统繁忙，稍后再试')
          }

      };

      var _test = function()
      { 
        var _timer = 0; 
          _timer++;
          var item = this;
        
          if(item.index)
          {
            console.log('第'+ _timer.toString() + '次:连接（探测）远程服务。');
            var _testUrl = item.host + item.index;
            Rsd.httpRequest({url:_testUrl,method:'GET',fail:function(){_textFail.call(item)}},{},function(data){_load.call(item,[data])},'连接远程服务');
          }
          else
          {
            _load.call(item,[{code:200}]);
          }
          
      };

      for(var i in servicesList)
      {
          var _s = servicesList[i];
          _s.api={};
          Rsd.services[_s.group]=_s;
          _test.call(_s);
      } 

  };
  /**
   * @description  加载controller 的方法
   * */
  Rsd.loadServiceApi = function loadServiceApi(service,callback) {

      if(Rsd.isEmpty(service.host))
      {
         console.error('host is null',service);
         return;
      }
      service.isLoading = true;

      var _group = service.group.toLowerCase();
      var _ssl = service.useSSL; 
      //console.log('load =>' + _group);
      var _url = service.host + service.controller + service.desc;
          Rsd.httpRequest({ url: _url}, {}, function(data) { 
              var list = data.data; 
              for(var j in list)
              {
                  var item = list[j];
                  //console.log(item);
                  if( _ssl && item.Url.startWith('http://'))
                  {
                      item.Url = 'https://' + item.Url.substr(7)
                  } 
                  var config = {
                      key:_group + '.' + item.MethodName.toLowerCase(),
                      name:item.MethodName.toLowerCase(), 
                      group:_group,
                      text:item.Description,
                      parent : Rsd.app,
                      errorHandler :service.errorHandler||'',
                      failureHandler : service.failureHandler||'',
                      successHandler : service.successHandler||'',
                      progressHandler: service.progressHandler||'',
                      ajaxType:service.ajaxType ||'ajax',
                      local:{method:'get',url:''},
                      server:{
                          url:item.Url,
                          method:item.Method || 'GET',
                          //contentType:'application/json',
                          //dataType: 'json',
                          async:item.IsAsync
                      }
                  }
                  Rsd.services[_group].api[item.MethodName.toLowerCase()] = config;
              }
  
              service.isLoading = false;
  
              //console.log('loaded =>' + _group);
              if(Rsd.isFunction(callback))
              {
                  callback.call(service,data);
              }
  
          },'加载服务');
  
  };

  /**
   *@description 上传文件 参数 url, file,name, args,callback
   */
  Rsd.uploadFile=function uploadFile(url, file,name, args,callback) {
    
      var _url = url || '';

      var service = Rsd.getService(_url);
       
      if (service) {
        _url = service.server.url;
      }
      else
      {
          return;
      }

      if (Rsd.isEmpty(_url)) {
          Rsd.warn('请设置上传地址');
          return;
      } 
      var app = Rsd.getApp();
      var _formData = args || {};
      
      //console.log(_formData); 
      //console.log( '上传文件('+ name+')');
       
      var uploadTask = wx.uploadFile({
        url: _url, //上传接口地址
        filePath: file,
        name: name,
        formData: _formData,
        "header": {
          'Content-Type': 'multipart/form-data;charset=utf-8',
          'token':app && app.token,
          'authorization':app && app.authorization
        },
        success: function(res){
          //console.log('success',res);
          //if(callback){
          //  callback(res);
          //}
        },
        complete:function(res){
          
            //console.log('complete',res);
            if(callback){ 
              callback(res);
            } 
        }
         
      });

      //进度监控
      uploadTask.onProgressUpdate(function(res){
        console.log( '文件('+ name+')上传进度', res.progress);

        //console.log(index +'-已经上传的数据长度', res.totalBytesSent);

        //console.log(index +'-预期需要上传的数据总长度', res.totalBytesExpectedToSend);

      });

    };
    /**
    * 上传多个文件 同步上传 
    *  list :[{file:'',name:'',args:{}}]
    */
   Rsd.uploadFiles = function uploadFiles(url,fileList,callback)
   { 
       var list = fileList||[];

      var _fn_upload = function(_url,_list,_index)
      { 
         if(_index == 0)
         {
           wx.showLoading({
             title: '图片上传中...',
           });
     
         } 
         var i = _index;
         
         if( i < _list.length)
         {
             var file = _list[i].url;
             var name = _list[i].name;
             var args = _list[i]; 
             
             var _fn = function(res){
    
                 _list[i].result = res;  
                 _fn_upload(_url,_list,i+1);
               
               };
   
             Rsd.uploadFile(_url, file,name, args,_fn);
              
             return;
         }
      
         //上传结束
         wx.hideLoading({
           complete: function(res)  {
             wx.showToast({
               title: '上传完成',
               icon: 'success',
               duration: 800
             });
           },
         });
         
         return ;
      }

      _fn_upload(url,list,0);

      if(callback)
      {
        callback(list);
      }
   };

  /**
  * @description 小程序更新升级
  * */
  Rsd.appUpdate=function appUpdate()
  {
      var hasUpdate = false;
      var updateManager = wx.getUpdateManager();

      updateManager.onCheckForUpdate(function (res) {
          // 请求完新版本信息的回调
          hasUpdate = res.hasUpdate;
      });
      //强制更新
      updateManager.onUpdateReady(function () {
          updateManager.applyUpdate();
      });
      //
      updateManager.onUpdateFailed(function () {
          // 新版本下载失败
      });

  }; 

  /**
   * @public
   * @description 写到本地缓存
   * @param {string} key
   * */
  Rsd.writeLocal = function writeLocal(key, value) {
      wx.setStorageSync(key, value);
  };

  /**
   * @public
   * @description 读取指定本地缓存
   * @param {string} key
   * */
  Rsd.readLocal = function readLocal(key) { 
      return wx.getStorageSync(key);
  };

  /**
   * @public
   * @description 清除指定本地缓存
   * @param {string} key
   * */
  Rsd.removeLocal = function removeLocal(key) {
      wx.removeStorageSync(key);
  };

  /**
   * @public
   * @description 清除所有本地缓存
   * */
  Rsd.clearLocal = function clearLocal() {
      wx.clearStorageSync();
  };
 /**
   *
   * @public
   * */
  Rsd.sleep = function sleep(msec) {
      var start = new Date().getTime();
      while (true) if (new Date().getTime() - start > msec) break;
  };
  /**
   * @public
   * */
  Rsd.toString = function toString(obj) {

      if (obj == undefined) {
          return "null";
      }
      var r = [];
      if (typeof obj == "string") {
          return "\"" + obj.replace(/([\"\\])/g, "\\$1").replace(/(\n)/g, "\\n").replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "\"";
      }
      if (typeof obj == "object") {
          if (!obj.sort) {

              for (var i in obj) {
                  if (typeof (obj[i]) == 'function') {
                      continue;
                  }
                  r.push("\"" + i + "\":" + Rsd.toString(obj[i]));
              }

              r = "{" + r.join() + "}"
          } else {
              for (var i = 0; i < obj.length; i++)
                  r.push(Rsd.toString(obj[i]))
              r = "[" + r.join() + "]";
          }
          return r;
      }

      return obj.toString().replace(/\"\:/g, '":""');
  };

   /**
   * @description 微信登陆 不涉及微信授权 通过code后端获取openid
   * @param {*} msg 登录描述信息
   */
  Rsd.login = function login(callback,msg)
  {  
      var me = this;   
       var _time = new Date().getTime();  
      var _span = _time - (me.loginTime||0);    
     
      //15分钟内的不重复登录
      if (_span < 15 * 1000 * 60) {   
            if(callback instanceof Function)
            {
                //console.log('注册事件afterLoggedin');
                me.on('afterLoggedin',callback);     
            }    
            return;
      }    
      //console.log(_span,'Login ==> ' + msg,callback);       
      //更新登录时间
      me.loginTime = new Date().getTime(); 
      var userInfo = wx.getStorageSync('userInfo');  
      if(userInfo)
      {  
          //验证token 是否有效
          var _token = userInfo['token']; 
          me.requestService('mission.account.checksession',{token: _token},function(resp)
          { 
              if(resp.success)
              {
                 me.fire('afterLoggedin',[userInfo]);  
              }
              else
              {
                  //session_key 已经失效，需要重新执行登录流程
                  //登录 通过code登陆
                  me.wxLogin(callback);
              }
          });
      }
      else
      {     
          me.wxLogin(callback);
      }
         
  };
  /**
   * 微信登录
   */
  Rsd.wxLogin = function wxLogin(callback)
  { 
      var me = this;
       //更新登录时间  
      me.loginTime = new Date().getTime();    
        //登录 通过code登陆，不需要用户授权
        wx.login({
          success: function(res)  { 
              // 发送 res.code 到后台换取 sessionKey,openId,  unionId 
              me.requestService('wxapp.login', { code: res.code }, function(resp){
                  if (resp.success) {
                      //缓存
                      var userInfo = resp.data.UserInfo;
                      userInfo.wxSessionKey = resp.data.WxSessionKey;
                      //设置用户信息
                      me.setUseInfo(userInfo['token'],userInfo);
                      //写日志
                      setTimeout(()=>{  
                        me.sendInfoLog('用户登录');
                      },0); 
                   
                      //回调
                      if(callback instanceof Function)
                      {
                          callback.call(me,userInfo); 
                      } 
                    
                  } 
              },'正在登录');

          },
          fail: function(res) { 
              me.sendErrorLog(res)
              console.error('wx.login', res);
             
          },
          complete: function(res){  
          }
      });
  };
  /**
   * 设置用户登录的会话信息
   * @param {*} token  会话token
   * @param {*} useInfo 用户信息
   */
  Rsd.setUseInfo = function setUseInfo(token,userInfo)
  {
       //api 请求设置到header中
       wx.setStorageSync('token',token); 
       //更新用户登录
       wx.setStorageSync('userInfo',userInfo);
       //console.log('触发事件afterLoggedin');
       this.fire('afterLoggedin',[userInfo]);  
  }
  /**
   * 发送app日志
   * @param {*} type  日志类型 debug,info,warn,error
   * @param {*} msg 
   */
  Rsd.sendAppLog = function sendAppLog(type,msg)
  {
     let app = this.getApp();
      var _data = { 
            from:app.refer,
            scene:app.scene,
            userId:app.userId,
            ticket:app.ticket,
            msg:msg||''
          };
         
          if(app && app.sendAppLog)
          {
            app.sendAppLog(type,_data);
          }else
          {
            console.error('app中未实现方法sendAppLog(type,data)',_data);
          }
        
  };
  /**
   * 发送调试日志
   * @param {*} msg 
   */
  Rsd.sendDebugLog = function sendDebugLog(msg)
  {
    this.sendAppLog('debug',msg);
  };
  /**
   * 发生普通日志
   * @param {*} msg 
   */
  Rsd.sendInfoLog = function sendInfoLog(msg)
  {
      this.sendAppLog('info',msg);
  };
  /**
   * 发送警告日志
   * @param {*} msg 
   */
  Rsd.sendWarnLog = function sendWarnLog(msg)
  {
    this.sendAppLog('warn',msg);
  };
  /***
   * 发送错误日志
   */
  Rsd.sendErrorLog = function sendErrorLog(msg)
  {
    this.sendAppLog('error',msg);
  };
     /**
      * @description (仅限在插件的组件和页面中使用)从page堆栈中获取page ，size=0 表示获取全部页面，size 默认值为 1
      * @param {*} size 
      * @param {*} callback 
      */
   Rsd.getPagesFromStackInPlugin = function getPagesFromStackInPlugin(){
        
        let pages = getCurrentPages(); 
       
        var list = [];
        for(var i = 0;i < pages.length;i++)
        {
            if(pages[i] == null)
            {
                list.push({text:'来自小程序页面，无权限访问系统返回null',route:''});
            }
            else
            {
                list.push(pages[i]);
            }
        }  
         
        
         
        return list; 
  };
  /**
   * 注册事件
   */
  Rsd.on = function on(name,fn)
  {
      let _name = name.toLocaleLowerCase();
      this.eventList = this.eventList||{};
      this.eventList[_name] = this.eventList[_name]||[];
      this.eventList[_name].push(fn);
  };
  /**
   * 触发事件
   */
  Rsd.fire = function fire(name,args)
  {
      var me = this; 
      if(!me.eventList)
      {
          setTimeout(function(){
              console.log("并发冲突，延时执行事件出发");
              me.fire(name,args);
          },100); 
          return;
      }
     
      let _name = name.toLocaleLowerCase(); 
      var list = me.eventList[_name] || []; 

      setTimeout(function(){
          list.map((fn, index) => { fn.apply(me, args) });
          me.eventList[_name] = [];
      }, 0);

      
  };
  
})();